<template>
  <div class="preview layout-card" v-loading="loading" element-loading-text="表单加载中...">
    <v-form-render
      v-if="!loading&&formJson"
      ref="vFormRef"
      :form-data="formData"
      :option-data="optionData"
      :global-dsv="designerDsv"
      :form-json="formJson"
      :preview-state="true"
    />
    <el-empty v-else :image-size="80" description="暂无数据"/>
  </div>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getFormInfo } from '@/api/form'

const route = useRoute()
const vFormRef = ref()
const formData = ref({})
const optionData = ref({})
const designerDsv = ref({})
const formJson = ref(null)
const loading = ref(false)

/**
 * URL参数示意
 * @query formKey 表单名称 [required]
 * @query token 认证token
 * @query sourceHost 数据源请求地址
 * @query remote 是否远程获取表单JSON数据
 */
const getData = () => {
  const { formKey, token, sourceHost, remote } = route.query
  if (!formKey) { return false }
  designerDsv.value = { formKey, token, sourceHost }
  formJson.value = null
  loading.value = true
  const isProd = process.env.NODE_ENV === 'production'
  const isRemote = String(remote) === 'true'
  if (isRemote) {
    getFormInfo(formKey as string).then(res => {
      respSuccess(res.data?.element)
    }).catch(respError)
  } else if (isProd) {
    axios.get(`../formFiles/${formKey}.json`).then(respSuccess).catch(respError)
  } else {
    import(`../../../public/formFiles/${formKey}.json`).then(res => {
      respSuccess(res.default)
    }).catch(respError)
  }
}
// eslint-disable-next-line
const respSuccess = (res: any) => {
  formJson.value = res
  loading.value = false
}
const respError = () => {
  loading.value = false
  ElMessage.error(`预览失败，找不到 ${route.query.formKey} 数据!`)
}

watchEffect(getData)
</script>

<style scoped lang="less">
.preview {
  min-height: 100%;
  background: #fff;
  padding: 15px;
  box-sizing: border-box;
}
</style>
